import { _SuperTable } from '@/.jiess/config.js';
import { isDef, querystring } from '@jiess/utils';
class RequestParse {
  constructor(url, param) {
    const { method, body } = param;
    this.method = method;
    this.url = new URL(url);
    this.records = [];
    // 需要带域名的url才能被解析
    const search = this.url.search.replace('?', '');
    this.query = querystring.parse(search);
    this.body = body && JSON.parse(body);
  }
  check(v) {
    return this.url.pathname.endsWith(v);
  }
  init(pathname, callback) {
    if (pathname && callback) {
      let { method, body, query, records } = this;
      method = method.toUpperCase();
      records.push(async (next) => {
        if (this.check(pathname)) {
          switch (method) {
            case 'POST':
              return callback(method, body, query);
            case 'PUT':
              return callback(method, body, query);
            case 'GET':
              return callback(method, query);
            case 'DELETE':
              return callback(method, query, body);
          }
        } else {
          return Promise.reject('匹配不成功');
        }
      });
    }
  }
  async build(callback) {
    const fn = this.init.bind(this);
    await callback.call(this, fn);
    for (let record of this.records) {
      try {
        const result = await record();
        if (result) return result;
      } catch (e) {
        // 匹配不成功
      }
    }
  }
  initId(param) {
    param?.list.forEach((v) => {
      // 对没有id的数据，初始化id
      if (!v.id) v.id = param.index++;
    });
  }
  // 构建通用table列表和查询接口
  tableList(url, param) {
    this.initId(param);
    this.init(url, (method, data) => {
      const { fieldDatas, fieldPageSize, fieldPage, fieldTotal } = _SuperTable;
      const other = {};
      let pageNum = 1;
      let pageSize = 10;
      for (const field in data) {
        if (field === fieldPageSize) {
          pageSize = data[fieldPageSize];
        } else if (field === fieldPage) {
          pageNum = data[fieldPage];
        } else {
          other[field] = data[field];
        }
      }
      // 提取有效字段
      const arrs = [];
      for (let field in other) {
        if (isDef(other[field], true)) {
          arrs.push(field);
        }
      }
      let list = param.list;
      if (arrs.length) {
        list = param.list.filter((dd) =>
          arrs.every((field) => {
            if (typeof dd[field] === 'string') {
              // 模糊匹配
              return dd[field].includes(other[field]);
            } else {
              // 等值匹配
              return dd[field] === other[field];
            }
          }),
        );
      }
      return {
        [fieldTotal]: list.length,
        [fieldDatas]: list.slice((pageNum - 1) * pageSize, pageNum * pageSize),
      };
    });
  }
  // 构建通用table增删改查接口
  tableOper(url, param) {
    this.initId(param);
    const arr = param.list;
    this.init(url, (method, data) => {
      if (method === 'POST') {
        arr.push(data);
        return (data.id = ++param.index);
      } else if (method === 'DELETE') {
        arr.splice(
          arr.findIndex((r) => r.id === data.id),
          1,
        );
      } else if (method === 'PUT') {
        Object.assign(
          arr.find((r) => r.id === data.id),
          data,
        );
      } else if (method === 'GET') {
        return arr.find((r) => r.id === data.id);
      }
    });
  }
}
export default RequestParse;
